package com.fy.common.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.AbstractCellStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @Description:
 * @Author: www
 * @Date: 2021/06/21 15:18
 */
public class HeadStyleWriteHandler extends AbstractCellStyleStrategy {


    /**
     *   复杂表头自定义样式队列，先进先出，方便存储
     * */
    private ArrayBlockingQueue<ComplexHeadStyles> headStylesQueue;
    /**
     *   WorkBoot
     * */
    private Workbook workbook;

    /**
     *   构造方法，创建对象时传入需要定制的表头信息队列
     *
     */
    public HeadStyleWriteHandler(ArrayBlockingQueue<ComplexHeadStyles> headStylesQueue){
        this.headStylesQueue=headStylesQueue;
    }


    @Override
    protected void initCellStyle(Workbook workbook) {
        // 初始化信息时，保存Workbook对象，转换时需要使用
        this.workbook=workbook;
    }

    @Override
    protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) {

        WriteCellStyle writeCellStyle=new WriteCellStyle();

        if(headStylesQueue !=null && ! headStylesQueue.isEmpty()){

            ComplexHeadStyles complexHeadStyle=headStylesQueue.peek();
            // 取出队列中的自定义表头信息，与当前坐标比较，判断是否相符
            if(cell.getColumnIndex() == complexHeadStyle.getY() && relativeRowIndex.equals(complexHeadStyle.getX())){
                // 设置自定义的表头样式
                writeCellStyle.setFillForegroundColor(complexHeadStyle.getIndexColor());
                // 样式出队
                headStylesQueue.poll();
            }
        }

        // WriteCellStyle转换为CellStyle
        CellStyle headCellStyle = StyleUtil.buildHeadCellStyle(workbook, writeCellStyle);
        // 设置表头样式
        cell.setCellStyle(headCellStyle);

    }

    @Override
    protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {

    }

}